package com.example.actionsignin.mvp.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.actionsignin.R;
import com.example.actionsignin.adapter.AddImageAdapter;
import com.example.actionsignin.constant.Constant;
import com.example.actionsignin.entity.LoginEntity;
import com.example.actionsignin.dialog.EndDateDialogFragment;
import com.example.actionsignin.dialog.RepeatFragment;
import com.example.actionsignin.dialog.StartDateDialogFragment;
import com.example.actionsignin.dialog.TypeDialogFragment;
import com.example.actionsignin.http.HttpUtil;
import com.example.actionsignin.mvp.model.DescribeInfo;
import com.example.actionsignin.mvp.model.ReleaseInfo;
import com.example.actionsignin.mvp.presenter.IReleaseListener;
import com.example.actionsignin.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 发布页面
 */
public class ReleaseActivity extends AppCompatActivity implements
        IReleaseListener,
        View.OnClickListener {

    private static final String TAG = "ReleaseActivity";
    private TextView mStartTimeText;
    private TextView mEndTimeText;
    private TextView mDescribeText;
    private TextView mPositionText;

    private TextView mType;

    private EditText mActionName;
    private LinearLayout linearLayout;

    private List<Map<String, Object>> mList = new ArrayList<>();
    private AddImageAdapter mGridAdapter;
    private GridView gridView;

    private double latitude;
    private double longitude;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);

        init();
        initGrid();
        getDialog();
    }

    private void initGrid() {
        mGridAdapter = new AddImageAdapter(this, mList);
        gridView.setAdapter(mGridAdapter);
    }

    private void init() {
        findViewById(R.id.release_mapView).setOnClickListener(this);
        findViewById(R.id.release_left).setOnClickListener(this);
        findViewById(R.id.date_start).setOnClickListener(this);
        findViewById(R.id.date_end).setOnClickListener(this);
        findViewById(R.id.action_describe).setOnClickListener(this);
        findViewById(R.id.release_release).setOnClickListener(this);

        mStartTimeText = (TextView) findViewById(R.id.date_start_text);
        mEndTimeText = (TextView) findViewById(R.id.date_end_text);
        mDescribeText = (TextView) findViewById(R.id.release_describe);
        gridView = (GridView) findViewById(R.id.release_gridView);
        mPositionText = (TextView) findViewById(R.id.release_action_position);
        mActionName = (EditText) findViewById(R.id.release_action_name);
        linearLayout = (LinearLayout) findViewById(R.id.activity_release_linear);
        mType = (TextView) findViewById(R.id.activity_release_type);

        if (mDescribeText.getText().equals("")) {
            mDescribeText.setText("暂无描述");
        }

        if (mPositionText.getText().equals("")) {
            mPositionText.setText("点击进入地图选择活动地点");
        }

        linearLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.release_left:
                ReleaseActivity.this.finish();
                break;
            case R.id.activity_release_linear:
                TypeDialogFragment typeDialogFragment = new TypeDialogFragment();
                typeDialogFragment.show(getSupportFragmentManager(),"typeDialog");
                break;
            case R.id.date_start:
                StartDateDialogFragment startDateDialogFragment = new StartDateDialogFragment();
                startDateDialogFragment.show(getSupportFragmentManager(), "startDateDialog");
                break;
            case R.id.date_end:
                EndDateDialogFragment endDateDialogFragment = new EndDateDialogFragment();
                endDateDialogFragment.show(getSupportFragmentManager(), "endDateDialog");
                break;
            case R.id.action_describe:
                Intent intent = new Intent(ReleaseActivity.this, ActionDescribeActivity.class);
                ReleaseActivity.this.startActivityForResult(intent, 1);
                break;
            case R.id.release_mapView:
                Intent intent1 = new Intent(ReleaseActivity.this, MapActivity.class);
                ReleaseActivity.this.startActivityForResult(intent1, 0);
                break;
            case R.id.release_release:
                releaseAction();
                break;
        }
    }

    @Override
    public void sendData(int id, Object data) {
        switch (id) {
            case 0:
                break;
            case 1:
                mStartTimeText.setText((CharSequence) data);
                break;
            case 2:
                mEndTimeText.setText((CharSequence) data);
                break;
            case 3:
                mType.setText((CharSequence) data);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    Bundle bundle = data.getExtras();
                    String address = bundle.getString("address");
                    if (address != null && !address.equals("")) {
                        mPositionText.setText(address);
                    }
                    Double lat = bundle.getDouble("latitude");
                    Double lng = bundle.getDouble("longitude");
                    if (lat != 0 || lng != 0) {
                        latitude = lat;
                        longitude = lng;
                    }

                    break;
                case 1:
                    Bundle bundle1 = data.getExtras();
                    DescribeInfo describeInfo = (DescribeInfo) bundle1.getSerializable("describe");
                    String describe = describeInfo.getDescribe();
                    List<Map<String, Object>> path_list = describeInfo.getList_path();
                    if (describe != null && !describe.equals("")) {
                        mDescribeText.setText(describe);
                    }
                    if (path_list != null && path_list.size() > 0) {
                        mList.clear();
                        mList.addAll(path_list);
                        mGridAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    private void releaseAction() {
        ReleaseInfo releaseInfo = new ReleaseInfo();
        String actionName = mActionName.getText().toString();
        if (actionName.equals("")) {
            ToastUtil.INSTANCE(this, "活动名称不能为空");
            return;
        }
        releaseInfo.setActionName(actionName);

        releaseInfo.setRepeat("");

        String startTime = mStartTimeText.getText().toString();
        if (startTime.equals("")) {
            ToastUtil.INSTANCE(this, "开始时间不能为空");
            return;
        }
        releaseInfo.setStartTime(startTime);

        String endTime = mEndTimeText.getText().toString();
        if (endTime.equals("")) {
            ToastUtil.INSTANCE(this, "结束时间不能为空");
            return;
        }
        releaseInfo.setEndTime(endTime);

        String actionPosition = mPositionText.getText().toString();
        if (actionPosition.equals("点击进入地图选择活动地点")) {
            ToastUtil.INSTANCE(this, "请选择活动地点");
            return;
        }
        releaseInfo.setActionAddress(actionPosition);
        releaseInfo.setLatitude(latitude);
        releaseInfo.setLongitude(longitude);

        String describe = mDescribeText.getText().toString();
        if (describe.equals("")) {
            ToastUtil.INSTANCE(this, "请填写活动介绍");
            return;
        }
        releaseInfo.setDescribe(describe);

        if (mList.size() > 0) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < mList.size(); i++) {
                list.add(String.valueOf(mList.get(i).get("path")));

            }
            releaseInfo.setPathList(list);
        }else {
            ToastUtil.INSTANCE(this,"请添加图片");
            return;
        }

        //设置签到类型
        for (int i = 0; i < Constant.TYPE_NAME.length; i++) {
            if (mType.getText().toString().equals(Constant.TYPE_NAME[i]))
            {
                releaseInfo.setType(String.valueOf(i));
            }
        }

        //发布活动
        sendInternet(releaseInfo);
    }

    private void sendInternet(ReleaseInfo releaseInfo) {

        File file1 = null;
        File file2 = null;
        File file3 = null;
        RequestBody body1 = null;
        RequestBody body2 = null;
        RequestBody body3 = null;
        if (releaseInfo.getPathList() != null)
        {
            if (releaseInfo.getPathList().size() == 0)
            {
                return;
            }
            if (releaseInfo.getPathList().size() >= 1)
            {
                file1 = new File(releaseInfo.getPathList().get(0));
                body1 = MultipartBody.create(MediaType.parse("image/jpg"),file1);
            }

            if (releaseInfo.getPathList().size() >= 2){
                file2 = new File(releaseInfo.getPathList().get(1));
                body2 = MultipartBody.create(MediaType.parse("image/jpg"),file2);
            }

            if (releaseInfo.getPathList().size() >= 3){
                file3 = new File(releaseInfo.getPathList().get(2));
                body3 = MultipartBody.create(MediaType.parse("image/jpg"),file3);
            }
        }else {
            ToastUtil.INSTANCE(this,"请添加图片");
            return;
        }

        if (file2 == null)
        {
            file2 = file1;
            body2 = body1;
        }
        if (file3 == null)
        {
            file3 = file1;
            body3 = body1;
        }

        dialog.show();

        HttpUtil.onSend().onRelease(releaseInfo.getActionName(),
                releaseInfo.getDescribe(),
                releaseInfo.getRepeat(),
                releaseInfo.getType(),
                releaseInfo.getStartTime(),
                releaseInfo.getEndTime(),
                releaseInfo.getActionAddress(),
                releaseInfo.getLatitude(),
                releaseInfo.getLongitude(),
                MultipartBody.Part.createFormData("image",file1.getName(),body1),
                MultipartBody.Part.createFormData("image",file2.getName(),body2),
                MultipartBody.Part.createFormData("image",file3.getName(),body3))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull LoginEntity loginEntity) {
                        dialog.dismiss();
                        if (loginEntity.getResult().equals("1")) {
                            finish();
                        } else {
                            ToastUtil.INSTANCE(getApplicationContext(), "发布失败");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d(TAG, "onError: " + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getDialog()
    {
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setTitle("提示");
        dialog.setMessage("正在发布...");
    }
}
